package com.wanban.download.exo;

import android.content.Context;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.database.DatabaseProvider;
import androidx.media3.database.StandaloneDatabaseProvider;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.datasource.HttpDataSource;
import androidx.media3.datasource.cache.Cache;
import androidx.media3.datasource.cache.CacheDataSource;
import androidx.media3.datasource.cache.CacheEvictor;
import androidx.media3.datasource.cache.NoOpCacheEvictor;
import androidx.media3.datasource.cache.SimpleCache;
import androidx.media3.exoplayer.offline.DownloadManager;
import androidx.media3.exoplayer.offline.DownloadNotificationHelper;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;
import androidx.media3.exoplayer.source.MediaSource;
import com.wanban.download.Params;
import com.wanban.download.utils.PathUtils;
import java.io.File;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.Executors;

/** Utility methods for the demo app. */
@UnstableApi
public final class DemoUtil {

    public static final String DOWNLOAD_NOTIFICATION_CHANNEL_ID = "download_channel";

    private static DataSource.Factory dataSourceFactory;
    private static HttpDataSource.Factory httpDataSourceFactory;
    private static DatabaseProvider databaseProvider;
    private static File downloadDirectory;
    private static Cache downloadCache;
    private static DownloadManager downloadManager;
    private static DownloadNotificationHelper downloadNotificationHelper;

    /** Returns whether extension renderers should be used. */
//    public static boolean useExtensionRenderers() {
//        return false;
//    }

//    public static RenderersFactory buildRenderersFactory(Context context, boolean preferExtensionRenderer) {
//        @DefaultRenderersFactory.ExtensionRendererMode
//        int extensionRendererMode =
//                useExtensionRenderers()
//                        ? (preferExtensionRenderer
//                        ? DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
//                        : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON)
//                        : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF;
//        return new DefaultRenderersFactory(context.getApplicationContext())
//                .setExtensionRendererMode(extensionRendererMode);
//    }

    public static synchronized HttpDataSource.Factory getHttpDataSourceFactory() {
        if (httpDataSourceFactory == null) {
            // We don't want to use Cronet, or we failed to instantiate a CronetEngine.
            CookieManager cookieManager = new CookieManager();
            cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
            CookieHandler.setDefault(cookieManager);
            httpDataSourceFactory = new M3u8HttpDataSource.Factory();
        }
        return httpDataSourceFactory;
    }

    /** Returns a {@link DataSource.Factory}. */
    public static synchronized DataSource.Factory getDataSourceFactory(Context context) {
        if (dataSourceFactory == null) {
            context = context.getApplicationContext();
            DefaultDataSource.Factory upstreamFactory = new DefaultDataSource.Factory(context, getHttpDataSourceFactory());
            dataSourceFactory = buildReadOnlyCacheDataSource(upstreamFactory, getDownloadCache(context));
        }
        return dataSourceFactory;
    }

    public static synchronized DownloadNotificationHelper getDownloadNotificationHelper(
            Context context) {
        if (downloadNotificationHelper == null) {
            downloadNotificationHelper = new DownloadNotificationHelper(context, DOWNLOAD_NOTIFICATION_CHANNEL_ID);
        }
        return downloadNotificationHelper;
    }

    public static synchronized DownloadManager getDownloadManager(Context context) {
        ensureDownloadManagerInitialized(context);
        return downloadManager;
    }

    public static synchronized Cache getDownloadCache(Context context) {
        if (downloadCache == null) {
            File downloadContentDirectory = getDownloadDirectory();
            CacheEvictor cacheEvictor = new NoOpCacheEvictor();
            downloadCache = new SimpleCache(
                    downloadContentDirectory,
                    cacheEvictor,
                    getDatabaseProvider(context)
            );
        }
        return downloadCache;
    }

    public static synchronized void ensureDownloadManagerInitialized(Context context) {
        if (downloadManager == null) {
            downloadManager = new DownloadManager(
                            context,
                            getDatabaseProvider(context),
                            getDownloadCache(context),
                            getHttpDataSourceFactory(),
                            Executors.newFixedThreadPool(/* nThreads= */ 10));
            downloadManager.setMaxParallelDownloads(3);
            downloadManager.setMinRetryCount(Params.MIN_DOWNLOAD_RETRY_TIMES);
        }
    }

    public static MediaSource.Factory getCacheMediaSourceFactory(Context context){
        DataSource.Factory dataSource = getDataSourceFactory(context);
        return new DefaultMediaSourceFactory(context).setDataSourceFactory(dataSource);
    }

    public static synchronized DatabaseProvider getDatabaseProvider(Context context) {
        if (databaseProvider == null) {
            databaseProvider = new StandaloneDatabaseProvider(context);
        }
        return databaseProvider;
    }

    public static synchronized File getDownloadDirectory() {
        if (downloadDirectory == null) {
            downloadDirectory = new File(PathUtils.INSTANCE.getMedia3RootPath());
        }
        return downloadDirectory;
    }

    public static CacheDataSource.Factory buildReadOnlyCacheDataSource(DataSource.Factory upstreamFactory, Cache cache) {
        return new CacheDataSource.Factory()
                .setCache(cache)
                .setUpstreamDataSourceFactory(upstreamFactory)
                .setCacheWriteDataSinkFactory(null)
                .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR);
    }

    private DemoUtil() {}

}